package br.com.sgmf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.sgmf.model.Peca;

@Repository
public class PecaDAO {

	@PersistenceContext
	private EntityManager manager;

	@Transactional
	public void save(Peca peca) {
		manager.persist(peca);
	}

	@Transactional
	public void update(Peca peca) {
		manager.merge(peca);
	}

	@Transactional
	public void delete(Peca peca) {
		peca = manager.merge(peca);
		manager.remove(peca);
	}

	@Transactional(readOnly = true)
	public Peca findById(Integer id) {
		return manager.find(Peca.class, id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Peca> findAll() {
		return manager.createQuery("select p from Peca p").getResultList();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Peca> findByNome(String nome) {
		return manager.createNamedQuery("Peca.findByNome")
				.setParameter("nome", "%" + nome + "%").getResultList();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Peca> findByNomeAndModelo(String nome, String modelo) {
		return manager.createNamedQuery("Peca.findByNomeAndModelo")
				.setParameter("nome", "%" + nome + "%")
				.setParameter("modelo", modelo).getResultList();
	}

}
